package com.chen.recruit.common.handler;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.chen.recruit.common.constants.SysConstants;
import com.chen.recruit.common.utils.SysUtils;
import com.chen.recruit.domain.model.BaseEntity;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.reflection.MetaObject;

import java.util.Date;

/**
 * mybatis-plus注入处理器
 *
 * @author cgy
 * @date 2022/09/04
 */
public class CreateAndUpdateMetaObjectHandler implements MetaObjectHandler {

    @Override
    public void insertFill(MetaObject metaObject) {
        if (ObjectUtil.isNotNull(metaObject) && metaObject.getOriginalObject() instanceof BaseEntity) {
            BaseEntity baseEntity = (BaseEntity) metaObject.getOriginalObject();
            Date current = ObjectUtil.isNotNull(baseEntity.getCreateTime()) ? baseEntity.getCreateTime() : new Date();
            baseEntity.setCreateTime(current);
            baseEntity.setUpdateTime(current);
            String createBy = baseEntity.getCreateBy();
            String username = StringUtils.isBlank(createBy) ? SysUtils.getLoginUser().getUsername() : createBy;
            baseEntity.setCreateBy(username);
            baseEntity.setUpdateBy(username);
            baseEntity.setVersion(SysConstants.INIT_VERSION);
        }
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        if (ObjectUtil.isNotNull(metaObject) && metaObject.getOriginalObject() instanceof BaseEntity) {
            BaseEntity baseEntity = (BaseEntity) metaObject.getOriginalObject();
            Date current = new Date();
            baseEntity.setUpdateTime(current);
            String username = SysUtils.getLoginUser().getUsername();
            if (StringUtils.isNotBlank(username)) {
                baseEntity.setUpdateBy(username);
            }
        }
    }

}
